package com.javasm.cloud.uaa.filter;

import com.google.common.collect.Lists;
import com.javasm.cloud.uaa.entity.AuthUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import sun.security.util.SecurityConstants;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            //解析请求参数 request.getQueryString()
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            if (antPathMatcher.match("/auth/oauth/authorize",request.getRequestURI())&& !ObjectUtils.isEmpty(username)&&!ObjectUtils.isEmpty(password)) {
                //参数中提取 clientId ，根据client 数据库查询用户信息进行身份认证
                String clientId = request.getParameter("client_id");
                //根据clientId查询用户信息 省略数据库用户信息查询
                //账号密码认证
                AuthUser authUser = new AuthUser();
                authUser.setUsername(username);
                authUser.setPassword(password);
                // 通过authenticationManager
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password, Lists.newArrayList());
                Authentication authentication = authenticationManager.authenticate(authenticationToken);
                // 认证成功后将认证信息存储到SpringSecurity上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            filterChain.doFilter(request, response);
            //在过滤器中添加return，是为了结束该方法的运行，也就是结束过滤
            return;
        }
    }
}